/**
 * @class c.Friend
 * @fileOverview 朋友列表控制器
 * @extends yijs.air.Controller
 */
var c = c || {};
c.Friends = function(options){
    this.config = options.config;
    this.lang = options.lang;
    this.cls = this.config.cls;
    this.controller = options.controller;
    this.action = this.config.actionCls.friends;
	this.field = this.config.field;
	//切换特效
	this.effect = this.config.effect;	
    //模型
    this.ModelOption = new Option();
	this.Model = new Friend();
	//模板路径
	this.viewPath = helpYi.getViewPath(this.config.viewName.friendsList);	
    //一页数据数
    this.limitNum = Number(this.ModelOption.get("number"));
	this.current = 1;
	this.page = 0;
    this.contentContainer = options.contentContainer;
	this.width = $(this.contentContainer).parent().width();
    this.Proxy = options.Proxy;
}
/**
 * 获取数据
 * @param {Boolean} isReadCache 是否读取数据库缓存数据
 * @param {Function} success 成功获取后的回调函数
 */
c.Friends.prototype.get = function(isReadCache,success){
	var _that = this;
	if(isReadCache){
		this.readCache();
	}else{
		//清除数据库缓存
		_that.clearCache();
		//重设当前页
		this.current = 1;		
		//预加载信息片段
		var _preLoadMsg = this.lang.friendList;	
		var _aMsg = _getPreloadMsg(_preLoadMsg);
		this.getCount(function(){
			_getFriends(function(){_that.creat();});	    
		})						
	}
	//处理预加载信息
	function _getPreloadMsg(_preLoadMsg){
		var _getMsg = _that.lang.get;
		var _completeMsg = _that.lang.complete;
		_beforeSendMsg = yijs.setTpl(_getMsg,_preLoadMsg);
		_successMsg = yijs.setTpl(_completeMsg,_preLoadMsg);
		return [_beforeSendMsg,_successMsg];		
	}
	
	//请求
	function _getFriends(complete){
			_that.Proxy.getFriends(function(data){
				_that.save(data);
				_that.current == _that.page-1 && complete && complete.call(this);
				if(_that.current < _that.page){
					_that.current ++;
					_getFriends();					
				}
			},_aMsg[0],_aMsg[1],_that.current);		
	}
	

	return this;
}
/**
 * 获取朋友数，并设置页数
 * @param {Function} success 成功获取后的回调函数
 */
c.Friends.prototype.getCount = function(success){
		var _that = this;
		this.Proxy.getFriendsCount(function(count){
			var _count = Number($(count).find(_that.field.count).text());
			//设置页数
			_that.page = Math.ceil(_count/_that.Proxy.count);
			success && success.call(this);							
		})
		return this;		
}
/**
 * 获取指定页的缓存数据
 * @param {Number} page	指定页数
 */
c.Friends.prototype.getCache = function(page){
	var _start = page * this.limitNum;
	var data = this.Model.get(this.controller,_start,this.limitNum);	
	return data;
}
/**
 * 获取缓存数据总页数
 * @param {Object} action
 */
c.Friends.prototype.getCacheCount = function(){
	var _num = this.Model.count(this.controller);
	var count = Math.ceil(_num/this.limitNum);
	return 	count;
}
/**
 * 创建列表
 */
c.Friends.prototype.creat = function(){
	var _that = this;
	//动作
	var _action = this.action;
	//清理缓存数据
	this.removeCacheData(_action);
	var _$action = $(this.contentContainer+" > ."+_action);
	if(_$action.size() == 0){
		//创建该动作下的容器	
		_$action = _that.createContainer(_action);
		//创建分页器
		var _Slider = this.createSlider(_action,function(val){
			_that.createList(val);
		});	
		//创建列表
		_that.createList(0);
		//设置动作容器宽度
		_setContainerWidth();					
	}
	//滚动到当前动作容器
	_contentSlideTo(_$action);
	
	/**
	 * 设置动作容器宽度
	 */
	function _setContainerWidth(){
		var _$c = $(_that.contentContainer).children();
		_$c.width(_that.width);
		$(_that.contentContainer).width(_$c.size() * _$c.width());			
	}	
	/**
	 * 滑动内容容器
	 * @param {Object} $action 动作容器
	 */
	function _contentSlideTo($action){
		var _index = $("."+_that.cls.actionItemsContainer).index($action);
		var _marginLeft = _index == 0 && 0 || "-"+_index*_that.width;	
		var _effet = {duration:_that.effect.content.duration,easing: _that.effect.content.easing};
		$(_that.contentContainer).animate({"marginLeft":_marginLeft},_effet);	
	}		
}
/**
 * 创建数据列表
 * @param {Number} page 指定页
 */
c.Friends.prototype.createList = function(page){
	var _that = this;
	var _renderTo = this.contentContainer+" > ."+this.action;
	var _$renderTo = $(_renderTo);
	var _cacheName = this.action+"_"+page;
	var _xml = null;
	if(_$renderTo.size() > 0){
		if(_$renderTo.data(_cacheName)){
			_xml = _$renderTo.data(_cacheName);
		}else{
			//读取数据
			var data = this.getCache(page);
			if(data && data.length > 0){
				//转成xml数据
				_xml = this.toXml(data,this.field.users,this.field.user);
				//将数据写入缓存
				_$renderTo.data(_cacheName,_xml);			
			}		
		}
		
		 removeList(_$renderTo.children("ul"),100,function(){
			//读取视图，并解析模板
			yijs.air.view(_xml,{url:_that.viewPath},_renderTo,function(xml,xsl){
				_viewHandler();	
			},true);		 	
		 });				
	}	
	
	function removeList($ul,delayTimer,fnCallBack){
		if($ul.size() > 0){
			var _$li = $ul.children("li"); 
			var _len = _$li.size();
			var _delayTimer = 0;
			_animate(_len-1);
			function _animate(eq){
				_$li.eq(eq).delay(_delayTimer).fadeOut("fast",function(){
					if(eq == 0){
						$ul.remove();
						fnCallBack && fnCallBack.call(this);
					}
				});
				if(eq == 0){
					return false;
				}else{
					_len = eq;
					_len --;	 
					_delayTimer += delayTimer;	
					_animate(_len);						
				}	
			}								
		}else{
			fnCallBack && fnCallBack.call(this);
		}
	}
	function _viewHandler(){
	    var $liOdd = _$renderTo.find("li:odd");
		$liOdd.addClass("status_odd");
		var $li = _$renderTo.find("li"); 
		var len = $li.size();
		var _delayTimer = 0;
		$li.each(function(){
			$(this).delay(_delayTimer).fadeIn("fast");
			_delayTimer += 200;
		})		
	}		
		
}
/**
 * 将数据保存到数据库
 * @param {Object} data			数据	
 * @param {Function} fnCallBack 回调函数
 */
c.Friends.prototype.save = function(data, fnCallBack){
	var _that = this;
    var _controller = this.controller;
    var _$user = $(data).find("user");
    if (_$user.size() > 0) {
        _$user.each(function(){
			var data = helpYi.formatFieldsJson(_that.field.friends,$(this).children());	
			data['controller'] = _controller;
			_that.Model.insert(data);
        })
        fnCallBack && fnCallBack.call(this);
    }
    return this;
}
/**
 * 删除数据库中的朋友信息
 */
c.Friends.prototype.clearCache = function(){
	this.Model.clear(this.controller);
	return this;
}
/**
 * 删除在动作容器上的数据缓存
 * @param {Object} action 动作名
 */
c.Friends.prototype.removeCacheData = function(){
	var _count = this.getCacheCount();
	var $cache = $(this.contentContainer + " > " +"."+this.action);
	var _cacheName = null;
	for(var i = 0;i < _count ; i++){
		_cacheName = this.action+"_"+i;
		$cache.removeData(_cacheName);
	}
	return 	true;
}

/**
 * 将从数据库查询返回的数据转换成xml
 * @param {Object} data 数据
 */
c.Friends.prototype.toXml = function(data,rootField,itemField){
	var _that = this;
	var _xml = null;
	if(data){
		_xml = helpYi.json2xml(data,rootField,itemField,function(key,value){
			if(key == "user_profile_image_url") return _that.formatFace(value);
			return value;
		});			
	}
	return _xml;
}
/**
 * 格式化头像输出
 * @param {String} face 头像路径
 */
c.Friends.prototype.formatFace = function(face){
	var _face = helpYi.formatFace(face, _that.config.faceSizes[1]);
	return '<img src="'+_face+'" width="48" height="48" />';	
}
/**
 * 创建一个动作容器
 */
c.Friends.prototype.createContainer = function(){
    var _action = this.contentContainer + " > ." + this.action;
    var _$action = $(_action);
    _$action.size() == 0 && $("<div />", {
        "class": this.action + " " + this.cls.actionItemsContainer
    }).appendTo(this.contentContainer);
    return $(_action);
}
/**
 * 创建分页滑动条
 * @param {String} action	动作
 */
c.Friends.prototype.createSlider = function(onslide){
	var _that = this;	
	var _$sliderRenderTo = this.contentContainer + " > " +"."+this.action;
	var _max = this.getCacheCount();
	var _Slider = new yijs.Slider({renderTo : _$sliderRenderTo,
								  width:100,
								  max:_max,
								  min:1,
								  listeners : {
								  	slide : function(val){
									   var _timer = setTimeout(function(){onslide && onslide.call(this,_Slider.value-1);clearTimeout(_timer)},700);
									}
								  }
								 });			
	_Slider.render();
	return 	_Slider;
}